<template>
  <div>
    <customDialog
      title="设置分销商apiKey"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="800"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-position="right"
          label-width="85px"
          class="form_box"
        >
          <el-row>
            <el-col :span="17">
              <el-form-item label="apiKey" prop="apiKey">
                <el-input
                  v-model="formData.apiKey"
                  placeholder="apiKey"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" style="margin-left: 10px">
              <el-button type="primary" @click="random"> 生成apiKey </el-button>
              <el-button type="primary" @click="copyLink(`${formData.apiKey}`)">
                复制
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="Ip白名单" prop="allowedIps">
                <el-tag
                  v-for="tag in formData.allowedIps"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button v-else size="small" @click="showInput">
                  + 输入ip白名单
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import { addTenant, updateTenant, getTenant } from "@/api/auth/index";
import {
  getApiKey,
  setApiKey,
  generate,
} from "@/api/operateCenter/distributor/index";
import type { FormInstance } from "element-plus";
import { ElInput } from "element-plus";
import { copyLink } from "@/utils/tools";
import { cloneDeep, debounce } from "lodash-es";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const form = {
  tenantId: undefined,
  apiKey: "",
  allowedIps: <any>[],
};
const formData = ref(Object.assign({}, form));
const inputValue = ref<string>("");
const inputVisible = ref<boolean>(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const fileRules = (rule: any, value: any, callback: any) => {
  const ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;
  // console.log("tags---", value, formData.value.allowedIps);

  if (!formData.value.allowedIps.length) {
    return callback(new Error("请填写ip白地址"));
  }
  // else if (!ipRegex.test(inputValue.value)) {
  //   return callback(new Error("请填写正确的ip地址"));
  // }
  callback();
};
const rules = reactive({
  apiKey: [
    { required: true, message: "请输入分销商的apiKey", trigger: "blur" },
  ],
  allowedIps: [{ required: true, validator: fileRules, trigger: "blur" }],
});

// 随机生成apiKey
const random = () => {
  generate().then((res: any) => {
    formData.value.apiKey = res?.data;
  });
};

// 关闭清除tag
const handleClose = (tag: string) => {
  if (tag) {
    formData.value.allowedIps.splice(formData.value.allowedIps.indexOf(tag), 1);
  }
};

// 显示input框
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

// 回车/失焦添加ip
const handleInputConfirm = () => {
  if (inputValue.value) {
    formData.value.allowedIps.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  Object.assign(formData.value, form);
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let submitD = {
        tenantId: formData.value.tenantId,
        params: {
          apiKey: formData.value.apiKey,
          allowedIps: formData.value.allowedIps,
        },
      };
      setApiKey(submitD).then(() => {
        ElMessage.success(`设置成功`);
        dialogVisible.value = false;
        emit("success");
        closeDialog(ruleFormRef.value);
      });
    }
  });
}, 150);

const getApiKeyData = (val: Record<string, any>) => {
  getApiKey(val.id).then((res: Record<string, any>) => {
    formData.value.tenantId = val?.id;
    formData.value.apiKey = res?.apiKey;
    formData.value.allowedIps = res?.allowedIps;
  });
};

// 父级电子显示dialog
const showDialog = async (val: any) => {
  // console.log("显示弹窗----", val);
  dialogVisible.value = true;
  if (val) {
    getApiKeyData(val);
  }
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;
}
</style>
